from flask import Flask, render_template, request
from flask import jsonify
from flask_cors import CORS
from cls_spider import get_news
from tushare_stock import TushareStock
from datetime import datetime, timedelta
from os import path
from stock_db import StockOB

app = Flask(__name__)
CORS(app, supports_credentials=True)
# 初始化数据库操作
db = StockOB()
# 初始化股票操作
ts = TushareStock()


@app.route("/")
def index():
    return render_template('index.html')


@app.route("/stock", methods=["POST"])
def stock():
    # 获取提交的股票代码、交易开始结束的时间
    rq_json = request.json
    stock_code = rq_json["code"].strip()
    start_time = rq_json["date1"]
    end_time = rq_json["date2"]
    # 判断传入的时间，如果为空替换为默认值
    if start_time:
        start_time = start_time.split("T")[0].replace("-", "")
    else:
        start_time = datetime.strftime(datetime.now() - timedelta(365), "%Y%m%d")
    if end_time:
        end_time = end_time.split("T")[0].replace("-", "")
    else:
        end_time = datetime.strftime(datetime.now() - timedelta(1), "%Y%m%d")
    # 获取股票数据,数据解释：时间，开盘价，收盘价，最低价，最高价
    # print(stock_code)
    get_stock_result = ts.get_stock(start_time, end_time, stock_code)

    if get_stock_result["status"] == 200:
        result = {
            "status": get_stock_result["status"],
            "stock_data": get_stock_result["stock_data"],
            "msg": get_stock_result["msg"]
        }
        return jsonify(result)
    else:
        result = {
            "status": get_stock_result["status"],
            "stock_data": None,
            "msg": get_stock_result["msg"]
        }
        return jsonify(result)


@app.route("/news", methods=["GET", "POST"])
def news():
    # 获取财经信息
    news_list = get_news()
    if news_list:
        result = {
            "status": 200,
            "news_info": news_list,
            "msg": "新闻获取成功！"
        }
    else:
        result = {
            "status": 201,
            "msg": "暂无新闻更新！"
        }
    return jsonify(result)


@app.route("/download", methods=["POST"])
def download():
    # 下载数据接口
    # 获取提交的股票代码、交易开始结束的时间
    rq_json = request.json
    stock_code = rq_json["code"]
    start_time = rq_json["date1"]
    end_time = rq_json["date2"]
    # 判断传入的时间，如果为空替换为默认值
    if start_time:
        start_time = start_time.split("T")[0].replace("-", "")
    else:
        start_time = datetime.strftime(datetime.now() - timedelta(365), "%Y%m%d")
    if end_time:
        end_time = end_time.split("T")[0].replace("-", "")
    else:
        end_time = datetime.strftime(datetime.now() - timedelta(1), "%Y%m%d")
    result = ts.download_stock(start_time, end_time, stock_code)
    if result["status"] == 200:
        return jsonify(result)
    else:
        return jsonify(result)


@app.route("/token", methods=["POST"])
def token():
    rq_json = request.json
    ts_token = rq_json["token"]
    # 获取当前 Python 模块文件的路径
    current_dir = path.dirname(path.abspath(__file__))
    # 构建 token.txt 文件的完整路径
    token_file = path.join(current_dir, "token.txt")
    if ts_token == "reset":
        # 默认的token在token.txt文件中
        with open(token_file, "r", encoding="utf-8") as f:
            ts_token = f.read()
        sql_result = db.insert_overwrite_token(ts_token)
        if sql_result["status"] == 200:
            return jsonify({
                "status": 200,
                "msg": "token重置成功！"
            })
        else:
            return jsonify(sql_result)
    else:
        sql_result = db.insert_overwrite_token(ts_token)
        if sql_result["status"] == 200:
            return jsonify({
                "status": 200,
                "msg": "token修改成功！"
            })
        else:
            return jsonify(sql_result)


if __name__ == '__main__':
    app.run(debug=True, port=8888)
    """
    浏览器自动打开页面：
    import webbrowser
    webbrowser.open("http://127.0.0.1:8888/")
    端口被占用: 
    lsof -i:8888
    kill pid
    打包命令：
    pip install pyinstaller
    pyinstaller -F --add-data="static;static" --add-data="templates;templates" --add-data="token.txt;." app.py
    """
